<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2023-09-23 13:44:31
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Models;

use App\Repositories\FinanceVoucherRepository;
use App\Traits\AttachmentTrait;
use App\Traits\AutoCodeTrait;
use App\Traits\VoucherTrait;

class FinanceReceiving extends BaseModel
    {
    use AttachmentTrait;
    use VoucherTrait;
    use AutoCodeTrait;
    public $timestamps = true;
    public $table = "sys_finance_receiving";
    protected $guarded = [];
    protected $ACSign = 'LENDER';
    protected $casts = [];
    public function subject()
        {
        return $this->belongsTo(Subject::class);
        }
    public function company()
        {
        return $this->belongsTo(Company::class);
        }
    public function tax()
        {
        return $this->belongsTo(Dic::class, "tax_id", "key")->where(function ($q)
            {
            $q->where("code", 'FinanceTax');
            });
        }
    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'status_with_finance');
            });
        }
    public function trade()
        {
        return $this->belongsTo(Trade::class);
        }

    public function finance($orders = null)
        {

        $gdata = $orders ?? $this;

        if ($gdata->status_id == 2)
            return $gdata->voucher;
        if ($gdata->status_id != 1) {
            fail("单据非审核状态！，无法财审！");
            }
        if (isEmpty($gdata->summary)) {
            $summary = ($gdata->state == 2 ? "付款" : "收款") . "-{$gdata->company->name} {$gdata->amount}元";
            }
        else
            $summary = $gdata->summary;
        $details = [];

        if ($gdata->state == 2) {
            //付款单
            //借 应付账款
            $details[] = FinanceVoucherRepository::mergeVoucher('2202', "[{$gdata->subject->name}]{$summary}", $gdata->amount, 0, $gdata->toArray());
            //贷 银行存款
            $details[] = FinanceVoucherRepository::mergeVoucher($gdata->subject_id, $summary, 0, $gdata->amount, $gdata->toArray());
            }
        else if ($gdata->state == 1) {
            //收款单
            //借 银行存款
            $details[] = FinanceVoucherRepository::mergeVoucher($gdata->subject_id, $summary, $gdata->amount, 0, $gdata->toArray());
            //贷 应收账款
            $details[] = FinanceVoucherRepository::mergeVoucher('1122', "[{$gdata->subject->name}]{$summary}", 0, $gdata->amount, $gdata->toArray());
            }
        else {
            fail("错误！请联系管理员");
            }
        //创建审核凭证
        $voucher = FinanceVoucherRepository::CreateVoucher($gdata->billdate, 1, $details, $gdata, $gdata->voucher?->id);
        auditSave($gdata, true, true, 2);
        return FinanceVoucherRepository::auditVoucher($voucher);
        }

    }
